﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Placid.PivotSourceImpl
{
    public class PivotSourceRowsCollection : IEnumerable<PivotSourceRow>
    {
        private PivotSource _container;
        private List<PivotSourceRow> _rows;
        private Dictionary<int, PivotSourceRow> _rowsByIndex;

        public PivotSourceRowsCollection(PivotSource container)
        {
            if(container != null) {
                _container = container;
            } else throw new Exception("IPvSource Container is a null reference.");

            _rows = new List<PivotSourceRow>();
            _rowsByIndex = new Dictionary<int, PivotSourceRow>();

            BuildRows();
        }

        private void BuildRows()
        {
            PivotSourceRow prow;
            DataRow dr;

            _rows.Clear();
            _rowsByIndex.Clear();

            for(int rowIndex = 0; rowIndex < _container._source.Rows.Count; rowIndex++) {
                dr = _container._source.Rows[rowIndex];
                prow = new PivotSourceRow(_container, rowIndex, rowIndex);
                _rowsByIndex.Add(rowIndex, prow);
                _rows.Add(prow);
            }
        }

        public void Clear()
        {
            _rows.Clear();
            _rowsByIndex.Clear();
        }

        public PivotSourceRow this[int index]
        {
            get
            {
                if(_rowsByIndex != null && _rowsByIndex.ContainsKey(index))
                    return _rowsByIndex[index];
                else throw new Exception("Row index " + index.ToString() + " not found.");
            }
        }

        public int Count
        {
            get
            {
                if(_rows != null) return _rows.Count;
                else return 0;
            }
        }

        #region IEnumerable<DSrcRow> Members

        public IEnumerator<PivotSourceRow> GetEnumerator()
        {
            if(_rows != null) {
                return _rows.GetEnumerator();
            } else {
                return null;
            }
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            if(_rows != null) {
                return _rows.GetEnumerator();
            } else {
                return null;
            }
        }

        #endregion
    }
}
